<template>
  <div class="markdown-editor">
    <!-- 标题和分类区域 -->
    <div class="header-section">
      <div class="title-input">
        <el-input v-model="title" placeholder="请输入文章标题" maxlength="100" show-word-limit />
      </div>
      <div class="category-select">
        <el-select v-model="selectedCategory" placeholder="请选择文章分类" clearable>
          <el-option v-for="category in categories" :key="category.value" :label="category.label"
            :value="category.value" />
        </el-select>
      </div>
    </div>

    <!-- 封面上传区域 -->
    <div class="cover-upload">
      <el-upload class="cover-uploader" action="" :show-file-list="false" :before-upload="beforeCoverUpload"
        :http-request="handleCoverUpload">
        <template v-if="coverUrl">
          <img :src="coverUrl" alt="封面图片" class="cover-image" />
          <div class="cover-overlay">
            <el-icon class="overlay-icon">
              <Camera />
            </el-icon>
            <span>更换封面</span>
          </div>
        </template>
        <template v-else>
          <div class="upload-placeholder">
            <el-icon class="cover-icon">
              <ImagePlus />
            </el-icon>
            <span class="upload-text">点击上传文章封面</span>
            <span class="upload-hint">建议尺寸：1200 x 600 像素</span>
          </div>
        </template>
      </el-upload>
      <div class="cover-tips">点击上传文章封面（建议尺寸：1200x600）</div>
    </div>

    <!-- 发布和取消按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handlePublish">发布帖子</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>

    <!-- 富文本编辑器 -->
    <mavon-editor ref="mdEditor" v-model="content" :toolbars="toolbars" :subfield="subfield" :defaultOpen="defaultOpen"
      :codeStyle="codeStyle" :ishljs="true" @imgAdd="handleImgAdd" @change="handleChange" class="editor-content" />

    <!-- 取消确认弹窗 -->
    <el-dialog v-model="cancelDialogVisible" title="确认取消" width="30%" center class="cancel-dialog">
      <div class="dialog-content">
        <el-icon class="warning-icon">
          <AlertTriangle />
        </el-icon>
        <span>确定要取消发布吗？所有未保存的内容将会丢失。</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">返回</el-button>
          <el-button type="danger" @click="confirmCancel">确认取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, defineExpose } from 'vue';
import { ElMessage, ElDialog } from 'element-plus';
import { ImagePlus, Camera, AlertTriangle } from 'lucide-vue-next';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: [String, Number],
    default: '500px'
  },
  autoSave: {
    type: Boolean,
    default: true
  },
  // 图片上传函数，需返回Promise
  uploadHandler: {
    type: Function,
    default: null
  },
  // 分类列表
  categories: {
    type: Array,
    default: () => [
      { value: '回收利用', label: '回收利用' },
      { value: '可持续饮食', label: '可持续饮食' },
      { value: '无包装购物', label: '无包装购物' },
      { value: '环保家居', label: '环保家居' },
    ]
  }
});

const emit = defineEmits(['update:modelValue', 'change', 'save', 'update:coverUrl', 'publish', 'cancel']);

// 编辑器实例
const mdEditor = ref(null);
const content = ref(props.modelValue);
const title = ref(''); // 文章标题
const cancelDialogVisible = ref(false); // 取消确认弹窗
const selectedCategory = ref(''); // 文章分类
const coverUrl = ref(''); // 文章封面
// 工具栏配置
const toolbars = {
  bold: true, // 粗体
  italic: true, // 斜体
  header: true, // 标题
  underline: true, // 下划线
  strikethrough: true, // 中划线
  mark: true, // 标记
  superscript: true, // 上角标
  subscript: true, // 下角标
  quote: true, // 引用
  ol: true, // 有序列表
  ul: true, // 无序列表
  link: true, // 链接
  imagelink: true, // 图片链接
  code: true, // code
  table: true, // 表格
  fullscreen: true, // 全屏编辑
  readmodel: true, // 沉浸式阅读
  htmlcode: true, // 展示html源码
  help: true, // 帮助
  undo: true, // 上一步
  redo: true, // 下一步
  trash: true, // 清空
  save: props.autoSave, // 保存（触发events中的save事件）
  navigation: true, // 导航目录
  subfield: true, // 单双栏模式
  preview: true, // 实时预览
};

// 编辑器配置
const subfield = ref(window.innerWidth > 768); // 响应式双栏模式
const defaultOpen = ref(window.innerWidth > 768 ? 'edit' : 'preview'); // 响应式默认视图
const codeStyle = ref('atom-one-dark'); // 代码样式

// 内容变化处理
const handleChange = (value, render) => {
  emit('update:modelValue', value);
  emit('change', { markdown: value, html: render });
};

// 图片添加处理
const handleImgAdd = async (pos, file) => {
  if (typeof props.uploadHandler === 'function') {
    try {
      const url = await props.uploadHandler(file);
      mdEditor.value.$img2Url(pos, url);
    } catch (error) {
      console.error('图片上传失败:', error);
    }
  } else {
    console.warn('未配置图片上传处理器');
  }
};

// 封面上传处理
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件！');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('封面图片大小不能超过5MB！');
    return false;
  }
  return true;
};

const handleCoverUpload = async (options) => {
  const { file } = options;
  if (typeof props.uploadHandler === 'function') {
    try {
      const url = await props.uploadHandler(file);
      coverUrl.value = url;
      emit('update:coverUrl', url);
      ElMessage.success('封面上传成功！');
    } catch (error) {
      ElMessage.error('封面上传失败，请重试！');
    }
  } else {
    ElMessage.warning('未配置图片上传处理器！');
  }
};

// 发布帖子
const handlePublish = () => {
  if (!title.value.trim()) {
    ElMessage.warning('请输入文章标题');
    return;
  }
  if (!content.value.trim()) {
    ElMessage.warning('请输入文章内容');
    return;
  }
  emit('publish', { title: title.value, content: content.value, coverUrl: coverUrl.value, tags: selectedCategory.value });
};

// 取消发布
const handleCancel = () => {
  cancelDialogVisible.value = true;
};

// 确认取消
const confirmCancel = () => {
  cancelDialogVisible.value = false;
  emit('cancel', false);
};

// 监听窗口大小变化，调整编辑器模式
window.addEventListener('resize', () => {
  if (window.innerWidth <= 768) {
    subfield.value = false;
    defaultOpen.value = 'preview';
  } else {
    subfield.value = true;
    defaultOpen.value = 'edit';
  }
});

// 暴露方法
defineExpose({
  getHtml: () => mdEditor.value?.render,
  getMarkdown: () => content.value,
  setContent: (val) => content.value = val,
  clear: () => {
    console.log('clear')
    content.value = ''
  },
});

// 监听父组件传值
watch(() => props.modelValue, (newVal) => {
  if (newVal !== content.value) {
    content.value = newVal;
  }
});
</script>

<style scoped lang="scss">
// 颜色变量
$primary-color: #10b981;
$primary-light: #d1fae5;
$primary-dark: #059669;
$secondary-color: #3b82f6;
$text-color: #1f2937;
$text-light: #6b7280;
$border-color: #e5e7eb;
$background-color: #f9fafb;
$danger-color: #ef4444;
$warning-color: #f59e0b;

.markdown-editor {
  display: flex;
  flex-direction: column;
  width: 100%;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

  @media (max-width: 768px) {
    width: 88vw;
    padding: 6px;
    margin: 0 auto;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
  }
}

.header-section {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;

  @media (max-width: 768px) {
    flex-direction: column;
    gap: 12px;

    .title-input {
      width: 100%;
    }

    .category-select {
      width: 100%;
    }
  }
  .title-input {
    flex: 1;

    :deep(.el-input__wrapper) {
      border-radius: 8px;
      background-color: $background-color;
      box-shadow: 0 0 0 1px $border-color;
      transition: all 0.2s ease;

      &:hover {
        box-shadow: 0 0 0 1px $primary-color;
      }

      &.is-focus {
        box-shadow: 0 0 0 1px $primary-color, 0 0 0 4px rgba($primary-color, 0.1) !important;
      }
    }

    :deep(.el-input__inner) {
      font-size: 16px;
      height: 44px;
      padding: 0 16px;

      @media (max-width: 768px) {
        font-size: 15px;
        height: 40px;
      }
    }

    :deep(.el-input__count) {
      background: transparent;
      color: $text-light;
      font-size: 12px;
    }
  }

  .category-select {
    width: 200px;

    @media (max-width: 768px) {
      width: 100%;
    }

    :deep(.el-select) {
      width: 100%;

      .el-input__wrapper {
        border-radius: 8px;
        background-color: $background-color;
        box-shadow: 0 0 0 1px $border-color;
        transition: all 0.2s ease;

        &:hover {
          box-shadow: 0 0 0 1px $primary-color;
        }

        &.is-focus {
          box-shadow: 0 0 0 1px $primary-color, 0 0 0 4px rgba($primary-color, 0.1) !important;
        }
      }

      .el-input__inner {
        height: 44px;

        @media (max-width: 768px) {
          height: 40px;
        }
      }
    }
  }
}

.cover-upload {
  margin-bottom: 24px;
  text-align: center;

  .cover-uploader {
    display: inline-block;
    border: 2px dashed $border-color;
    border-radius: 12px;
    cursor: pointer;
    overflow: hidden;
    width: 100%;
    max-width: 600px;
    height: 300px;
    background-color: $background-color;
    transition: all 0.3s ease;
    position: relative;

    @media (max-width: 768px) {
      height: 200px;
      border-radius: 8px;
    }

    &:hover {
      border-color: $primary-color;
      background-color: rgba($primary-color, 0.05);
    }

    .cover-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 10px;
      transition: transform 0.3s ease;
    }

    .cover-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.4);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: white;
      opacity: 0;
      transition: opacity 0.3s ease;

      .overlay-icon {
        font-size: 32px;
        margin-bottom: 8px;

        @media (max-width: 768px) {
          font-size: 24px;
        }
      }

      span {
        font-size: 14px;
        font-weight: 500;
      }
    }

    &:hover .cover-overlay {
      opacity: 1;
    }

    &:hover .cover-image {
      transform: scale(1.05);
    }

    .upload-placeholder {
      margin-top: 100px;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      @media (max-width: 768px) {
        margin-top: 50px;
      }
      .cover-icon {
        font-size: 40px;
        color: $text-light;
        margin-bottom: 10px;

        @media (max-width: 768px) {
          font-size: 32px;
        }
      }

      .upload-text {
        font-size: 16px;
        color: $text-color;
        margin-bottom: 8px;

        @media (max-width: 768px) {
          font-size: 14px;
          margin-bottom: 4px;
        }
      }

      .upload-hint {
        font-size: 12px;
        color: $text-light;

        @media (max-width: 768px) {
          font-size: 11px;
        }
      }
    }
  }

  .cover-tips {
    margin-top: 12px;
    font-size: 13px;
    color: $text-light;

    @media (max-width: 768px) {
      font-size: 12px;
      margin-top: 8px;
    }
  }
}

.editor-content {
  width: 100%;
  flex: 1;
  margin: 0 auto;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid $border-color;
  margin-bottom: 24px;

  @media (max-width: 768px) {
    border-radius: 8px;
    margin-bottom: 16px;
  }

  :deep(.v-note-wrapper) {
    z-index: 1;

    .v-note-panel {
      border: none !important;
    }

    .v-note-edit-wrapper,
    .v-note-show-wrapper {
      padding: 16px;

      @media (max-width: 768px) {
        padding: 12px;
      }
    }

    .v-note-op {
      border-bottom: 1px solid $border-color !important;

      .v-left-item,
      .v-right-item {
        margin: 5px !important;

        .op-icon {
          padding: 6px !important;

          @media (max-width: 768px) {
            padding: 4px !important;
          }
        }
      }
    }
  }
}

.action-buttons {
  margin-bottom: 20px;
  text-align: right;

  @media (max-width: 768px) {
    display: flex;
    flex-direction: column-reverse;
    gap: 12px;
  }

  .el-button {
    margin-left: 10px;
    border-radius: 8px;
    padding: 10px 20px;
    font-size: 14px;
    transition: all 0.3s ease;
    height: 44px;

    @media (max-width: 768px) {
      margin-left: 0;
      width: 100%;
      height: 40px;
    }

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    &:active {
      transform: translateY(0);
    }
  }

  .el-button--primary {
    background-color: $primary-color;
    border-color: $primary-color;

    &:hover {
      background-color: $primary-dark;
      border-color: $primary-dark;
      box-shadow: 0 4px 12px rgba($primary-color, 0.3);
    }
  }
}

.cancel-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 20px 10px;
    text-align: center;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  :deep(.el-dialog__body) {
    padding: 10px 20px 20px;
  }

  .dialog-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;

    .warning-icon {
      font-size: 48px;
      color: $warning-color;
      margin-bottom: 16px;
    }

    span {
      font-size: 15px;
      color: $text-color;
      line-height: 1.5;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 12px;

    @media (max-width: 480px) {
      flex-direction: column-reverse;
      gap: 8px;
    }

    .el-button {
      min-width: 100px;

      @media (max-width: 480px) {
        width: 100%;
      }
    }

    .el-button--danger {
      background-color: $danger-color;
      border-color: $danger-color;

      &:hover {
        background-color: darken($danger-color, 10%);
        border-color: darken($danger-color, 10%);
      }
    }
  }
}

@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    max-width: 400px;
  }
}
</style>
